<?php

namespace App\Http\Controllers\Backend\Auth;

use Illuminate\Http\Request;
use App\Http\Controllers\Backend\Controller;
use Illuminate\Support\Facades\View;
use App\Services\Auth\ModuleButtonService;
use App\Services\Auth\ModuleService;
use App\Entities\Auth\ModuleButton;

class ModuleButtonController extends Controller
{
    protected $service;
    protected $moduleService;
    protected $services;

    public function __construct(ModuleButtonService $service, ModuleService $moduleService)
    {
        $this->service = $service;
        $this->moduleService = $moduleService;
        $this->baseViewAddress = 'backend.auth.module_button.';
    }

    public function list()
    {
        return response()->json($this->service->getPageList());
    }

    public function tree()
    {
        return response()->json($this->service->getTree());
    }

    public function index($module_id)
    {
        $module = $this->moduleService->show($module_id);

        return View::make($this->baseViewAddress.'index', compact('module'));
    }

    public function create($module_id)
    {
        $button = new ModuleButton();
        $button->module_id = $module_id;

        return View::make($this->baseViewAddress.'create', compact('button'));
    }

    public function store(Request $request)
    {
        if ($this->service->create($request->all())) {
            return redirect(route('admin.auth.module.button.index', ['module_id' => $request->get('module_id')]))->with(['status' => '添加成功']);
        }

        return redirect(route('admin.auth.module.button.index', ['module_id' => $request->get('module_id')]))->with(['status' => '系统错误']);
    }

    public function show($id)
    {
        $button = $this->service->show($id);

        return View::make($this->baseViewAddress.'show', compact('button'));
    }

    public function edit($id)
    {
        $button = $this->service->show($id);

        return View::make($this->baseViewAddress.'edit', compact('button'));
    }

    public function update(Request $request, $id)
    {
        if ($this->service->update($id, $request->all())) {
            return redirect(route('admin.auth.module.button.index'))->with(['status' => '更新成功']);
        }

        return redirect(route('admin.auth.module.button.index'))->withErrors(['status' => '系统错误']);
    }

    public function destroy()
    {
        $ids = request()->get('ids');

        if (empty($ids)) {
            return response()->json(['code' => 1, 'msg' => '请选择删除项']);
        }
        if ($this->service->remove($ids)) {
            return response()->json(['code' => 0, 'msg' => '删除成功']);
        }

        return response()->json(['code' => 0, 'msg' => '删除失败']);
    }
}
